package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Voice;
import com.tanhua.dubbo.server.service.IdService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


/**
 * @Author fenda xu
 * @Date 2021 3/28/21 9:40 PM
 * @Version 1.0
 */
@Service(version = "1.0.0")
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

 @Autowired
    private IdService idService;


    /**
     * 保存语音
     *
     * @param voice
     * @return
     */
    @Override
    public Boolean saveVoice(Voice voice) {

        //校验
        if (!ObjectUtil.isAllNotEmpty(voice.getUserid(), voice.getSoundFileUrl())) {
            return null;
        }

        voice.setId(ObjectId.get());
        voice.setVid(idService.createId(IdType.VOICE));
        voice.setCreate(System.currentTimeMillis());
        mongoTemplate.save(voice);

        return true;
    }


    /**
     * 获得语音集合
     *
     * @return
     */
    @Override
    public List<Voice> getVoice() {
        List<Voice> voiceList = mongoTemplate.findAll(Voice.class);

        return voiceList;
    }

    /**
     * 通过语音id获取语音
     *
     * @return
     */
    @Override
    public Voice getVoiceByVid(String vid) {

        Query query = Query.query(Criteria.where("vid").is(Integer.parseInt(vid)));

        Voice voiceOne = mongoTemplate.findOne(query, Voice.class);
        return voiceOne;
    }

    @Override
    public List<Voice> getVoiceByCreated() {


        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("create")));

        List<Voice> voiceList = mongoTemplate.find(query, Voice.class);

        return voiceList;
    }


}
